package com.yunlong.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.sun.mail.util.MailSSLSocketFactory;
import com.yunlong.dto.MessageDto;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.List;
import java.util.Properties;


/**
 * @author guorui
 * @date 2020-07-24 14:47
 */
@Slf4j
@Component
public class MessageUtil {

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    static final String accessKeyId = "LTAI4G2w1vPZ7VZ7CkLsoeJL";
    static final String accessKeySecret = "P5PVDqWzjEDsTpwHQgkHfXTHEF462K";
    int phoneCode;

    /**
     * 阿里云发送手机短信验证码通用模板
     *
     * @param number
     * @param TemplateCode  模板管理里的模板编号
     * @param TemplateParam 模板中的变量替换JSON串，此处为验证码，可以自定义验证码的形式
     * @return
     */

    public MessageDto getSsmAll(String number, String TemplateCode, String TemplateParam) {

        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        } catch (ClientException e1) {
            e1.printStackTrace();
        }
        IAcsClient acsClient = new DefaultAcsClient(profile);

//        //随机生成六位验证码
//        int code = (int) ((Math.random() * 9 + 1) * 100000);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(number);
        //必填:短信签名-可在短信控制台中找到，你在签名管理里的内容
        request.setSignName("Dresults");
        //必填:短信模板-可在短信控制台中找到，你模板管理里的模板编号
        request.setTemplateCode(TemplateCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam("{\"code\":\"" + TemplateParam + "\"}");

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        //request.setOutId("yourOutId");

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        //获取发送状态
        MessageDto messageDto = new MessageDto(TemplateParam, sendSmsResponse.getCode());

        return messageDto;
    }

    /**
     * 发送手机验证码实现方法，注意模板
     *
     * @param number
     * @return
     */
    public MessageDto getSsm(String number,String phoneCode) {
        return getSsmAll(number, "SMS_197885114", phoneCode);
    }


    @SneakyThrows
    public MessageDto sendEmail(String email, String subject, String content) {
        //guorui的邮箱服务密码
        String liVerifCode = "rnglseedrzdjgefh";
        // 发件人电子邮箱
        String from = "1142456160@qq.com";
        // 指定发送邮件的主机为 smtp.qq.com
        //QQ 邮件服务器
        String host = "smtp.qq.com";
        // 获取系统属性
        Properties properties = System.getProperties();
        // email是收件人电子邮箱
        String to = email;
        // 设置邮件服务器
        try {
            properties.setProperty("mail.smtp.host", host);
            properties.put("mail.smtp.auth", "true");
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);
            // 获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("1142456160@qq.com", liVerifCode); //发件人邮件用户名、授权码
                }
            });
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);
            // Set From: 头部头字段
            message.setFrom(new InternetAddress(from));
            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // Set Subject: 头部头字段
            message.setSubject(subject);
            // 设置消息体
            message.setText(content);
            // 发送消息
            Transport.send(message);
        } catch (AddressException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        MessageDto messageDto = new MessageDto(content, true);
        log.info(email + ":" + content);
        return messageDto;

    }

    @SneakyThrows
    public void sendManyEmail(List<String> emails,String subject, String content){
        //逐个发送邮件
        for (String email:emails){
            sendEmail(email,subject,content);
        }
    }

    @SneakyThrows
    public MessageDto sendEmailOfRegister(String email,String code) {

        String subject = "欢迎注册会议室管理系统";
        if(sendEmail(email, subject, code).isOk()==true){
            MessageDto messageDto = new MessageDto(code, true);
//        redisRepository.saveEmailMessageCode(email, String.valueOf(code));
            log.info(email + ":  发送了一条验证码");
            return messageDto;
        }else {
            MessageDto messageDto = new MessageDto(code, false);
            return messageDto;
        }
    }
}
